#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的惠农网农产品价格实时展示Web仪表板
"""

from flask import Flask, jsonify, request
import redis
import json
import time
from datetime import datetime
import logging

app = Flask(__name__)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Redis配置
REDIS_CONFIG = {
    'host': '192.168.88.130',
    'port': 6379,
    'db': 0,
    'password': '123456',
    'decode_responses': True
}

class DataManager:
    def __init__(self):
        self.redis_client = None
        self.connect_redis()
    
    def connect_redis(self):
        try:
            self.redis_client = redis.Redis(**REDIS_CONFIG)
            self.redis_client.ping()
            logger.info("Redis连接成功")
        except Exception as e:
            logger.error(f"Redis连接失败: {e}")
            self.redis_client = None
    
    def get_latest_prices(self, limit=50):
        if not self.redis_client:
            return []
        
        try:
            keys = self.redis_client.keys('cnhnb_price:*')
            if not keys:
                return []
            
            data_list = []
            for key in keys:
                try:
                    data = self.redis_client.get(key)
                    if data:
                        item = json.loads(data)
                        data_list.append(item)
                except Exception as e:
                    logger.warning(f"解析数据失败 {key}: {e}")
            
            data_list.sort(key=lambda x: x.get('timestamp', 0), reverse=True)
            return data_list[:limit]
            
        except Exception as e:
            logger.error(f"获取价格数据失败: {e}")
            return []

# 全局数据管理器
data_manager = DataManager()

@app.route('/')
def index():
    return '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农网农产品价格实时监控</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
        .container { background: rgba(255,255,255,0.95); border-radius: 20px; margin: 20px; padding: 30px; }
        .header { text-align: center; margin-bottom: 30px; color: #2c3e50; }
        .price-card { background: white; border-radius: 15px; padding: 20px; margin-bottom: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); }
        .product-name { font-size: 1.2rem; font-weight: 600; color: #2c3e50; }
        .price-value { font-size: 1.5rem; font-weight: 700; color: #e74c3c; }
        .location { color: #3498db; font-weight: 500; }
        .timestamp { color: #95a5a6; font-size: 0.9rem; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>惠农网农产品价格实时监控</h1>
            <p>实时监控全国农产品价格行情</p>
        </div>
        
        <div class="row mb-4">
            <div class="col-md-6">
                <button class="btn btn-primary" onclick="refreshData()">刷新数据</button>
                <span id="status" class="ms-3">检查状态...</span>
            </div>
            <div class="col-md-6 text-end">
                <span id="lastUpdate"></span>
            </div>
        </div>
        
        <div id="priceData">
            <div class="text-center">正在加载数据...</div>
        </div>
    </div>

    <script>
        async function loadData() {
            try {
                const response = await fetch('/api/latest_prices?limit=20');
                const data = await response.json();
                
                if (data.success) {
                    displayPriceData(data.data);
                    document.getElementById('lastUpdate').textContent = '最后更新: ' + new Date().toLocaleString();
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                document.getElementById('status').textContent = '连接错误';
            }
        }

        function displayPriceData(data) {
            const container = document.getElementById('priceData');
            
            if (data.length === 0) {
                container.innerHTML = '<div class="text-center text-muted">暂无数据</div>';
                return;
            }

            const html = data.map(item => `
                <div class="price-card">
                    <div class="row align-items-center">
                        <div class="col-md-3">
                            <div class="product-name">${item.name}</div>
                        </div>
                        <div class="col-md-2">
                            <span class="price-value">${item.price_value}</span> 元/${item.unit}
                        </div>
                        <div class="col-md-3">
                            <span class="location">${item.location}</span>
                        </div>
                        <div class="col-md-2">
                            <span class="timestamp">${formatTime(item.crawl_timestamp)}</span>
                        </div>
                        <div class="col-md-2">
                            <a href="${item.source_url}" target="_blank" class="btn btn-sm btn-outline-primary">查看</a>
                        </div>
                    </div>
                </div>
            `).join('');

            container.innerHTML = html;
        }

        function refreshData() {
            loadData();
        }

        function formatTime(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }

        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadData();
            // 每10秒自动刷新
            setInterval(loadData, 10000);
        });
    </script>
</body>
</html>
    '''

@app.route('/api/latest_prices')
def api_latest_prices():
    limit = request.args.get('limit', 50, type=int)
    data = data_manager.get_latest_prices(limit)
    return jsonify({
        'success': True,
        'data': data,
        'count': len(data),
        'timestamp': datetime.now().isoformat()
    })

if __name__ == '__main__':
    import argparse
    
    parser = argparse.ArgumentParser(description='惠农网价格数据Web仪表板')
    parser.add_argument('--host', default='0.0.0.0', help='监听地址')
    parser.add_argument('--port', type=int, default=5000, help='监听端口')
    
    args = parser.parse_args()
    
    logger.info(f"启动Web服务器: http://{args.host}:{args.port}")
    app.run(host=args.host, port=args.port) 